var gulp = require('gulp');
var uglify = require('gulp-uglify');
var less = require('gulp-less');
var rename = require('gulp-rename');
var browserSync = require('browser-sync');
var minifycss = require("gulp-clean-css");
var replace = require("gulp-replace");
var clean = require('gulp-clean');
var config = require("./gulpConfig.json");
var tinypng = require("gulp-tinypng");
var changed = require("gulp-changed");
var spritesmith = require("gulp-spritesmith");
var gulpif = require("gulp-if");
var gulpSequence = require('gulp-sequence');
var plumber = require('gulp-plumber');
var imagemin = require('gulp-imagemin');
var imageminOptipng = require('imagemin-optipng');
var build_dest = "dist/";
var reload = browserSync.reload;

//tinypng key
// uRVGZmA9VJR1G8uSkp0u8EHFJzv8H6xE
// FcPzd9s4J06pVz0LjocQVWhkgKKH5R0T
var tinypng_api_key = "uRVGZmA9VJR1G8uSkp0u8EHFJzv8H6xE";

//编译main.less
//将 ../../ 路径替换成 ../
var lessTask = function(){
    return gulp.src(config.desktop.less.src)
        .pipe(plumber())
        .pipe(less())
        .pipe(rename({ extname: '.css' }))
        .pipe(replace("../../","../"))
        .pipe(plumber.stop())
        .pipe(gulp.dest(config.desktop.less.dest));
};

gulp.task('compile:less', function(){
    return lessTask();
});

//图片压缩
//开发时不自动压缩
//请开手动挡
gulp.task("image:build",function(){
    return gulp.src(config.desktop.image.src)
        .pipe(plumber())
        .pipe(tinypng(tinypng_api_key))
        .pipe(plumber.stop())
        .pipe(gulp.dest(build_dest));
});

gulp.task('imagemin', function(){
    return gulp.src(config.desktop.image.src)
        .pipe(imagemin({
            progressive: true,
            use: [imageminOptipng({optimizationLevel: 1})]
        }))
        .pipe(gulp.dest(build_dest));
});

//临时压缩一些图片，并覆盖
//gulp.task("image-test",function(){
//    return gulp.src(["dev/**/images/index/banner1.png","dev/**/images/index/bg1.png","dev/**/images/index/bg2.png"],{base:"./"})
//        .pipe(tinypng(tinypng_api_key))
//        //.pipe(rename({"suffix":".min"}))
//        .pipe(gulp.dest("./"));
//});

//压缩 tinypng 目录下图片
gulp.task("image-others",function(){
    return gulp.src(["tinypng/**/*.png","tinypng/**/*.jpg","tinypng/**/*.jpeg"],{base:"./"})
        .pipe(tinypng(tinypng_api_key))
        //.pipe(rename({"suffix":".min"}))
        .pipe(gulp.dest("./"));
});

//生成图片精灵
//需先清除生成的 .db 文件
gulp.task("sprites", ["clean:cache"], function(cb){
    return gulp.src(config.desktop.sprites.src)
        .pipe(spritesmith({
            imgName: 'sprite.png',
            styleName: 'sprite.css',
            imgPath: '../images/sprite.png',
            algorithm:"top-down",
            padding: 20
        }))
        .pipe(gulpif("*.png", gulp.dest(config.desktop.sprites.dest.img)))
        .pipe(gulpif('*.css', gulp.dest(config.desktop.sprites.dest.css)));
});

gulp.task("watch",function(){
    gulp.watch(config.desktop.less.watch,function(e){
        if(e.type != "error"){
            console.log("compile less");
            lessTask();
        } else {
            console.log("error");
        }
    });
    gulp.watch(config.desktop.sprites.watch,["sprites"]);
});

//日常开发自动编译less，生成雪碧图，压缩js
//手动刷新
gulp.task("development", function(cb){
    var stream = gulpSequence(["compile:less", "sprites"], "clean:cache","watch",cb);

    return stream;
});

//自动挡
gulp.task("browsersync", ["development"], function(cb){
    browserSync({
        server: {
            baseDir: 'dev'
        }
    });

    //watch();
    //文件变动时刷新浏览器
    gulp.watch(config.desktop.serve.watch,reload);
});

//构建时，先删除dist
gulp.task("clean:dist",function(){
    return gulp.src(build_dest)
        .pipe(clean({read: false}));
});

//清除缓存、错误文件
//gulp.task("clean:error",function(){
//    return gulp.src(config.desktop.clean.error.src)
//        .pipe(clean({read: false}));
//});

gulp.task("clean:cache",function(){
    return gulp.src(config.desktop.clean.cache.src)
        .pipe(clean({read: false}));
});

//构建时拷贝
//拷贝时排除css文件
gulp.task("copy:build",function(){
    return gulp.src(config.desktop.build_copy.src)
            .pipe(gulp.dest(build_dest));
});

//build时，压缩CSS
gulp.task('css:build',function(){
    return gulp.src(config.desktop.css.src)
        .pipe(minifycss({
            "advanced ":true,
            "compatibility": "ie7"
        }))
        .pipe(gulp.dest(build_dest));
});

//js压缩
gulp.task("scripts:build",function(){
    return gulp.src(config.desktop.scripts.src)
        .pipe(uglify())
        .pipe(gulp.dest(build_dest));
        //.pipe(rename({"suffix":".min"}))
        //.pipe(gulp.dest(build_dest));
});

//打包构建
gulp.task('build', function(cb) {
    //顺序执行
    //1、先清理dist目录
    //2、并行执行less编译、图片精灵、js压缩
    //3、图片压缩
    //3、拷贝到dist目录
    //4、压缩css，拷贝到dist
    gulpSequence(["clean:dist","clean:cache"],["compile:less","sprites"], "copy:build",["css:build"])(cb);
});